package com.andy.process.threadpool;

import com.alibaba.druid.pool.DruidDataSource;
import com.andy.common.constant.Constant;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by Administrator on 2017/9/1.
 */
public class Connector {
    private static Logger LOG = LoggerFactory.getLogger(Connector.class);
    private final DruidDataSource dataSource;
    volatile private static Connector connector = null;
//    private final boolean autoCommit;
    private final String url;
    private final String userName;
    private final int maxIdle;
    private final String passWord;

    private Connector(Properties prop) {
//        autoCommit = Boolean.valueOf(prop.get(Constant.JDBC.autoCommit).toString());
        url = String.valueOf(prop.get(Constant.JDBC.url));
        userName = String.valueOf(prop.get(Constant.JDBC.userName));
        maxIdle = Integer.valueOf(100);
        passWord = String.valueOf(prop.get(Constant.JDBC.passWord));
        dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        dataSource.setMaxActive(maxIdle);
//        dataSource.setDefaultAutoCommit(autoCommit);
        dataSource.setAsyncCloseConnectionEnable(true);
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    }

    public static Connector getInstance(Properties properties) {
        synchronized (Connector.class) {
            if (connector == null) {
                connector = new Connector(properties);
            }
        }
        return connector;
    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            LOG.error("dataSource getConnection error, error is {}", e);
        }
        return null;
    }
}
